package com;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.common.constant.SharesConstan;
import com.common.utils.HttpClient5Utils;
import com.common.utils.MeUtils;
import com.common.utils.StringUtil;
import com.entity.SharesData;
import com.entity.SharesDetail;
import com.service.SharesDataService;
import com.service.SharesDetailService;
import com.vo.SharesTimeVo;
import com.vo.SharesZdfVo;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;

@SpringBootTest
// 让 JUnit 运行 Spring 的测试环境， 获得 Spring 环境的上下文的支持
@RunWith(SpringRunner.class)
public class ModelDemo {


    @Autowired
    private SharesDataService sharesDataService;

    @Autowired
    private SharesDetailService sharesDetailService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 每周初始化
     */
    @Test
    public void getInit() {
        //清理数据
        Wrapper<SharesDetail> wrd = new EntityWrapper<>();

        List<SharesDetail> sharesDetails = sharesDetailService.selectList(wrd);
        Wrapper<SharesDetail> wr = new EntityWrapper<>();
        sharesDetailService.delete(wr);

        List<SharesDetail> saveList = new ArrayList<>();
        for (SharesDetail sharesDetail : sharesDetails) {
            SharesDetail vo = new SharesDetail();
            vo.setCode(sharesDetail.getCode());
            vo.setName(sharesDetail.getName());
            vo.setSshy(sharesDetail.getSshy());
            vo.setSsgn(sharesDetail.getSsgn());
            vo.setMagical(sharesDetail.getMagical());
            vo.setStatus(88);
            saveList.add(vo);
        }
        sharesDetailService.insertBatch(saveList);
//
        Wrapper<SharesData> wrdd = new EntityWrapper<>();
        sharesDataService.delete(wrdd);
        //获取周数据 //获取上周收盘价
        sharesDataService.getWeekData();
        //获取月数据//获取上月收盘价
        sharesDataService.getMonthData();
//        计算周涨幅 //记录周涨幅
        sharesDataService.getzzf();
        //计算月涨幅  //记录月涨幅
        sharesDataService.getyzf();
    }


    /**
     * 获取最近一年左右的数据信息
     */
    @Test
    public void getDataByYear() {

    }

    /**
     * 计算月涨幅
     * 最近一年的
     */
    @Test
    public void getMData() {

        Wrapper<SharesDetail> wrd = new EntityWrapper<>();
        wrd.eq("status", 88);
        List<SharesDetail> sharesDetails = sharesDetailService.selectList(wrd);
        List<SharesData> upDataShares = new ArrayList<>();
        for (SharesDetail sharesDetail : sharesDetails) {
            Wrapper<SharesData> wr = new EntityWrapper<>();
            wr.eq("type", SharesConstan.MONTH);
            wr.gt("time", "2020-11-21");
            wr.eq("code", sharesDetail.getCode());
            System.out.println(sharesDetail.getCode());
            List<SharesData> sharesDatas = sharesDataService.selectList(wr);
            for (int i = 1; i < sharesDatas.size() - 1; i++) {
                SharesData sharesData1 = sharesDatas.get(i - 1);
                BigDecimal cPrice1 = sharesData1.getCPrice();
                SharesData sharesData = sharesDatas.get(i);
                BigDecimal cPrice = sharesData.getCPrice();
                if (cPrice.compareTo(cPrice1) == -1) {
                    continue;
                }
                BigDecimal mzf = MeUtils.calculateTrend(cPrice.toString(), cPrice1.toString());
                sharesData.setZdf(mzf.toString());
                upDataShares.add(sharesData);
            }
        }
        sharesDataService.updateBatchById(upDataShares);

    }

    /**
     * 计算周涨幅
     * 最近3个月。3*4=12
     */
    @Test
    public void getz() {

        Wrapper<SharesDetail> wrd = new EntityWrapper<>();
        wrd.eq("status", 88);
        List<SharesDetail> sharesDetails = sharesDetailService.selectList(wrd);

        for (SharesDetail sharesDetail : sharesDetails) {
            Wrapper<SharesData> wr = new EntityWrapper<>();
            wr.eq("type", SharesConstan.WEEK);
            wr.gt("time", "2021-06-07");
            wr.eq("code", sharesDetail.getCode());
            System.out.println(sharesDetail.getCode());
            List<SharesData> sharesDatas = sharesDataService.selectList(wr);
            List<SharesData> upDataShares = new ArrayList<>();

            for (int i = 1; i < sharesDatas.size(); i++) {
                SharesData sharesData1 = sharesDatas.get(i - 1);
                BigDecimal cPrice1 = sharesData1.getCPrice();

                SharesData sharesData = sharesDatas.get(i);
                BigDecimal cPrice = sharesData.getCPrice();

                if (cPrice.compareTo(cPrice1) == -1) {
                    continue;
                }
                BigDecimal mzf = MeUtils.calculateTrend(cPrice.toString(), cPrice1.toString());
                sharesData.setZdf(mzf.toString());
                upDataShares.add(sharesData);

            }
            if (!CollectionUtils.isEmpty(upDataShares)) {
                sharesDataService.updateBatchById(upDataShares);
            }
        }


    }

    /**
     * 获取历史月涨幅
     */
    @Test
    public void getzfm() {
        Wrapper<SharesDetail> wr = new EntityWrapper<>();
        wr.eq("status", "88");
//        wr.isNull("yzf");
        List<SharesDetail> sharesDetails = sharesDetailService.selectList(wr);
        List<SharesDetail> updateShares = new ArrayList<>();
        //获取周振幅较大的
        for (SharesDetail sharesDetail : sharesDetails) {
            Wrapper<SharesData> wrs = new EntityWrapper<>();
            wrs.eq("type", SharesConstan.MONTH);
            wrs.gt("time", "2020-11-07");
            //    wr.gt("time","2021-06-07");
            wrs.eq("code", sharesDetail.getCode());
            wrs.isNotNull("zdf");
            List<SharesData> sharesDatas = sharesDataService.selectList(wrs);
            if (!CollectionUtils.isEmpty(sharesDatas)) {
                List<SharesZdfVo> zdfVos = new ArrayList<>();
                for (SharesData sharesData : sharesDatas) {
                    SharesZdfVo sharesZdfVo = new SharesZdfVo();
                    sharesZdfVo.setD(sharesData.getTime());
                    sharesZdfVo.setZdf(sharesData.getZdf());
                    zdfVos.add(sharesZdfVo);
                }
                String s = JSONArray.toJSONString(zdfVos);
                sharesDetail.setYzf(s);
                updateShares.add(sharesDetail);
            }
        }
        sharesDetailService.updateBatchById(updateShares);
        System.out.println("dd");
    }


    /**
     * 更新周涨幅数据
     */
    @Test
    public void getzfz() {

        Wrapper<SharesDetail> wr = new EntityWrapper<>();
        wr.eq("status", "88");
//        wr.isNull("zzf");
        List<SharesDetail> sharesDetails = sharesDetailService.selectList(wr);
        //获取周振幅较大的
        List<SharesDetail> updateShares = new ArrayList<>();
        for (SharesDetail sharesDetail : sharesDetails) {
            Wrapper<SharesData> wrs = new EntityWrapper<>();
            wrs.eq("type", SharesConstan.WEEK);
//            wrs.gt("time","2020-11-07");
            wrs.gt("time", "2021-06-07");
            wrs.eq("code", sharesDetail.getCode());
            wrs.isNotNull("zdf");
            List<SharesData> sharesDatas = sharesDataService.selectList(wrs);
            if (!CollectionUtils.isEmpty(sharesDatas)) {
                List<SharesZdfVo> zdfVos = new ArrayList<>();
                for (SharesData sharesData : sharesDatas) {
                    SharesZdfVo sharesZdfVo = new SharesZdfVo();
                    sharesZdfVo.setD(sharesData.getTime());
                    sharesZdfVo.setZdf(sharesData.getZdf());
                    zdfVos.add(sharesZdfVo);
                }
                String s = JSONArray.toJSONString(zdfVos);
                sharesDetail.setZzf(s);
                updateShares.add(sharesDetail);
            }
        }
        sharesDetailService.updateBatchById(updateShares);

    }

    /**
     * 寻找出周涨幅超过百分之20的区间，涨幅低于百分之5的时候的走势
     */
//    @Test
//    public void getzzfh(){
//        Wrapper<SharesData> wr=new EntityWrapper<>();
//        wr.eq("type",SharesConstan.WEEK);
//        wr.gt("zdf","19");
//        List<SharesData> sharesData = sharesDataService.selectList(wr);
//        for (SharesData sharesDatum : sharesData) {
//            String zdf = sharesDatum.getZdf();
//            String time = sharesDatum.getTime();
//
//            Wrapper<SharesData> wrd=new EntityWrapper<>();
//            List<SharesData> sharesDs = sharesDataService.selectList(wrd);
//            for (SharesData sharesD : sharesDs) {
//                if (new BigDecimal(sharesD.getZdf()).compareTo(new BigDecimal(5)) == -1) {
//                    //寻找出这个一天，往后开始涨的时候，
//                    //然后寻找出涨百分只5以上的走势
//                }
//            }
//        }
//    }

    /**
     * 前一天的走势
     * 统计当天最高点达到百分之5涨幅的时候
     * 今天的走势，和明天涨的概率
     */
    @Test
    public void getm5trend() {
//        Wrapper<SharesData> wrd=new EntityWrapper<>();
//        wrd.eq("type",SharesConstan.M5);
//        wrd.in("status","j,m,z");
//        wrd.orderBy("id");
//        List<SharesData> sharesDs = sharesDataService.selectList(wrd);
//
//        Map<String, List<SharesData>> map=new HashMap<>();
//        for (SharesData sharesD : sharesDs) {
//            sharesD.getTime();
//        }


        Wrapper<SharesDetail> wr = new EntityWrapper<>();
        wr.isNotNull("zftime");
        List<SharesDetail> sharesDatas = sharesDetailService.selectList(wr);

        int add = 0;
        int total = 0;
        for (SharesDetail sharesData : sharesDatas) {
            try {
                String zftime = sharesData.getZftime();
                List<SharesTimeVo> sharesTimeVos = JSONArray.parseArray(zftime, SharesTimeVo.class);

                for (SharesTimeVo sharesTimeVo : sharesTimeVos) {
//                String jtime = sharesTimeVo.getJtime();
                    String mzf = sharesTimeVo.getMzf();
                    String zzj = sharesTimeVo.getZzj();
                    if (!StringUtil.isEmpty(mzf) && !StringUtil.isEmpty(zzj)) {

                        if (new BigDecimal(zzj).compareTo(new BigDecimal(0)) == 1) {
                            if (new BigDecimal(mzf).compareTo(new BigDecimal(0)) == -1) {
                                add++;
                            }
                            total++;
                        }

                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println(sharesData.getCode());
            }

        }

        System.out.println(add);
        System.out.println(total);
    }

    /**
     * 5分钟接口
     */
    @Test
    public void getm5medol() {

        Wrapper<SharesDetail> wr = new EntityWrapper<>();
        wr.isNotNull("zftime");
        List<SharesDetail> sharesDetails = sharesDetailService.selectList(wr);

        for (SharesDetail sharesDetail : sharesDetails) {
            String szftime = sharesDetail.getZftime();
            List<SharesTimeVo> sharesTimeVos = JSONArray.parseArray(szftime, SharesTimeVo.class);
            //查询5分钟的数据

            Set<String> setTime = new HashSet<>();
            for (SharesTimeVo sharesTimeVo : sharesTimeVos) {
                setTime.add(sharesTimeVo.getZtime());
                setTime.add(sharesTimeVo.getJtime());
                setTime.add(sharesTimeVo.getMtime());
            }

            Map<String, List<SharesData>> map = new TreeMap<>();

            String szorsh = sharesDetail.getCode();
            String name = sharesDetail.getName();
            String substring = szorsh.substring(2);
            System.out.println(szorsh + "=" + sharesDetail.getId());
            if (substring.startsWith("688")) {
                continue;
            }
            if (name.contains("st")) {
                continue;
            }
            String url = "";
            if (szorsh.contains("sz")) {
                url = "http://17.push2his.eastmoney.com/api/qt/stock/kline/get" +
                        "?cb=jQuery112407991803491462504_1636097949492" +
                        "&secid=0." + substring +
                        "&ut=fa5fd1943c7b386f172d6893dbfba10b&fields1=f1%2Cf2%2Cf3%2Cf4%2Cf5%2Cf6&fields2" +
                        "=f51%2Cf52%2Cf53%2Cf54%2Cf55%2Cf56%2Cf57%2Cf58%2Cf59%2Cf60%2Cf61&klt=5&fqt" +
                        "=0&end=20500101&lmt=1000000&_=" + new Date().getTime();
            }

            if (szorsh.contains("sh")) {
                url = "http://17.push2his.eastmoney.com/api/qt/stock/kline/get" +
                        "?cb=jQuery112407991803491462504_1636097949492" +
                        "&secid=1." + substring +
                        "&ut=fa5fd1943c7b386f172d6893dbfba10b&fields1=f1%2Cf2%2Cf3%2Cf4%2Cf5%2Cf6&fields2" +
                        "=f51%2Cf52%2Cf53%2Cf54%2Cf55%2Cf56%2Cf57%2Cf58%2Cf59%2Cf60%2Cf61&klt=5&fqt" +
                        "=0&end=20500101&lmt=1000000&_=" + new Date().getTime();

            }

            try {
                HttpGet get = new HttpGet(url);
                CloseableHttpResponse execute = HttpClient5Utils.httpclient.execute(get);
                String result = EntityUtils.toString(execute.getEntity(), "UTF-8");
                int rIndex = result.indexOf("(");
                String resultStr = result.substring(rIndex + 1, result.length() - 2);
                JSONObject datas2 = JSONObject.parseObject(resultStr);
                String data = datas2.getString("data");
                String klines = JSONObject.parseObject(data).getString("klines");
                List<Object> parse = (List<Object>) JSON.parse(klines);
                List<SharesData> sharesDatas = sharesDataService.saveCjl(parse, szorsh, name, SharesConstan.M5, "");

                List<SharesData> sharesDataList = new ArrayList<>();
                if (!CollectionUtils.isEmpty(sharesDatas)) {
                    for (SharesData sharesData : sharesDatas) {
                        String time = sharesData.getTime();
                        for (String s : setTime) {
                            if (time.startsWith(s)) {
                                sharesDataList.add(sharesData);
                                List<SharesData> vo1 = map.get(szorsh + s);
                                if (!CollectionUtils.isEmpty(vo1)) {
                                    vo1.add(sharesData);
                                    map.put(szorsh + s, vo1);
                                } else {
                                    List<SharesData> vo2 = new ArrayList<>();
                                    vo2.add(sharesData);
                                    map.put(szorsh + s, vo2);
                                }
                            }
                        }
                    }
                }

                if (!CollectionUtils.isEmpty(map)) {
//                        sharesDataService.insertBatch(sharesDataList);
                    redisTemplate.opsForValue().multiSet(map);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        String cjlTrend = "";//成交量
        String zfTrend = "";
    }

    /**
     * 模型
     */
    @Test
    public void get() {

        Map<String, Integer> mmp = new TreeMap<>();
        Map<String, Integer> jmmp = new TreeMap<>();

        Wrapper<SharesDetail> wr = new EntityWrapper<>();
        wr.isNotNull("zftime");
        List<SharesDetail> sharesDatas = sharesDetailService.selectList(wr);

        int add = 0;
        int total = 0;
        int sub = 0;
        for (SharesDetail sharesData : sharesDatas) {
            try {
                String zftime = sharesData.getZftime();
                List<SharesTimeVo> sharesTimeVos = JSONArray.parseArray(zftime, SharesTimeVo.class);

                for (SharesTimeVo sharesTimeVo : sharesTimeVos) {
                    System.out.println(sharesTimeVo.getZzj() + "---" + sharesTimeVo.getJzf() + "---" + sharesTimeVo.getMzf());
                }
//                for (SharesTimeVo sharesTimeVo : sharesTimeVos) {
//                    String mzf = sharesTimeVo.getMzf();
//                    String zzj = sharesTimeVo.getZzj();
//                    if(!StringUtil.isEmpty(mzf)&&!StringUtil.isEmpty(zzj)){
//                        if(new BigDecimal(zzj).compareTo(new BigDecimal(0))==-1){
//                            continue;
//                        }
//                            if(new BigDecimal(mzf).compareTo(new BigDecimal(0))==-1){
//                                List<SharesData> list = (List<SharesData>)redisTemplate.opsForValue().get(sharesData.getCode() + sharesTimeVo.getJtime());
//                                if(!CollectionUtils.isEmpty(list)){
//                                    //计算成交量比
//                                  String cjlTrend= getcjlTrend(list);
//                                    Integer integer = mmp.get(cjlTrend);
//                                    if(null==integer){
//                                        mmp.put(cjlTrend,1);
//                                    }else{
//                                       mmp.put(cjlTrend,integer+1);
//                                    }
//                                }
//                                add++;
//                            }else{
//                                List<SharesData> list = (List<SharesData>)redisTemplate.opsForValue().get(sharesData.getCode() + sharesTimeVo.getJtime());
//                                if(!CollectionUtils.isEmpty(list)){
//                                    //计算成交量比
//                                    String cjlTrend= getcjlTrend(list);
//                                    Integer integer = jmmp.get(cjlTrend);
//                                    if(null==integer){
//                                        jmmp.put(cjlTrend,1);
//                                    }else{
//                                        jmmp.put(cjlTrend,integer+1);
//                                    }
//                                }
//                                sub++;
//                            }
//                            total++;
//                    }
//                }
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println(sharesData.getCode());
            }

        }

//        for (String s : mmp.keySet()) {
//            System.out.println(s+"======="+mmp.get(s)+"----"+jmmp.get(s)+"*****"+(mmp.get(s)+0.0d)/jmmp.get(s));
//        }
        System.out.println(add);
        System.out.println(sub);
        System.out.println(total);
    }

    private String getcjlTrend(List<SharesData> dataList) {
        BigDecimal tcjl = new BigDecimal(0);
        for (SharesData sharesData : dataList) {
            tcjl = tcjl.add(new BigDecimal(sharesData.getCjl()));
        }
        StringBuffer sb = new StringBuffer();
        BigDecimal bigDecimal = tcjl.divide(new BigDecimal(48), 0, BigDecimal.ROUND_HALF_UP);

        //百分之5时，出现在第几个

        int m = 0;
        for (int i = 0; i < dataList.size() - 1; i++) {
            BigDecimal kPrice = dataList.get(0).getKPrice();
            BigDecimal hPrice = dataList.get(i).getHPrice();
            BigDecimal zf = MeUtils.calculateTrend(hPrice.toString(), kPrice.toString());

            if (zf.compareTo(new BigDecimal(0.05)) == 1) {
                m = i;
                break;
            }
        }

        return m + "";

//        for (SharesData sharesData : dataList) {
//            BigDecimal kPrice = sharesData.getKPrice();
//            BigDecimal cPrice = sharesData.getCPrice();
//            BigDecimal hPrice = sharesData.getHPrice();
//            BigDecimal dPrice = sharesData.getDPrice();
//            String cjl = sharesData.getCjl();
//
//            BigDecimal kczf = MeUtils.calculateTrend(cPrice.toString(), kPrice.toString());
//            BigDecimal hdzf = MeUtils.calculateTrend(hPrice.toString(), dPrice.toString());
//
//            BigDecimal[] bs1 = new BigDecimal(cjl).divideAndRemainder(bigDecimal);
//            System.out.println(bs1[0]);
//            sb.append(bs1[0]);
//            //成交量变化情况，240/5=48
//            //最高点出现在什么地方
//            //百分之5得时候出现在在什么地方
//            //拉升情况
//            //成交量翻倍的情况
//        }
    }
}
